<?php

namespace backend\modules\rbac\models;

use Yii;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "auth_item".
 *
 * @property string $name
 * @property int $type
 * @property string $description
 * @property string $rule_name
 * @property resource $data
 * @property int $created_at
 * @property int $updated_at
 *
 * @property AuthAssignment[] $authAssignments
 * @property AuthRule $ruleName
 * @property AuthItemChild[] $authItemChildren
 * @property AuthItemChild[] $authItemChildren0
 * @property AuthItem[] $children
 * @property AuthItem[] $parents
 */
class AuthItem extends \yii\db\ActiveRecord
{
    const TYPE_ROLE = 1;
    const TYPE_PERMISSION = 2;

    public function behaviors(){
        return [
            [
                'class'=>TimestampBehavior::class,
            ]
        ];
    }

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'auth_item';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['name', 'type'], 'required', 'on'=>'insert'],
            [['type', 'created_at', 'updated_at'], 'integer'],
            [['description', 'data'], 'string'],
            [['name', 'rule_name'], 'string', 'max' => 64],
            [['name'], 'unique'],
            [['rule_name'], 'exist', 'skipOnError' => true, 'targetClass' => AuthRule::className(), 'targetAttribute' => ['rule_name' => 'name']],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'name' => 'Name',
            'type' => 'Type',
            'description' => 'Description',
            'rule_name' => 'Rule Name',
            'data' => 'Data',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAuthAssignments()
    {
        return $this->hasMany(AuthAssignment::className(), ['item_name' => 'name']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRuleName()
    {
        return $this->hasOne(AuthRule::className(), ['name' => 'rule_name']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAuthItemChildren()
    {
        return $this->hasMany(AuthItemChild::className(), ['parent' => 'name']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAuthItemChildren0()
    {
        return $this->hasMany(AuthItemChild::className(), ['child' => 'name']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getChildren()
    {
        return $this->hasMany(AuthItem::className(), ['name' => 'child'])->viaTable('auth_item_child', ['parent' => 'name']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getParents()
    {
        return $this->hasMany(AuthItem::className(), ['name' => 'parent'])->viaTable('auth_item_child', ['child' => 'name']);
    }

    public static function RoleNamesVsDescription()
    {
        $result = [];
        $data = self::find()->where(['type'=>self::TYPE_ROLE])->select(['name', 'description'])->all();
        foreach ($data as $value){
            $result[$value->name] = $value->description;
        }
        return $result;
    }

    public static function PermissionNamesVsDescription()
    {
        $result = [];
        $data = self::find()->where(['type'=>self::TYPE_PERMISSION])->select(['name', 'description'])->all();
        foreach ($data as $value){
            $result[$value->name] = $value->description;
        }
        return $result;
    }

    /**
     * @desc 获取树形checkbox 数组
     * @param $permissions
     * @param array $role_permissions
     * @return array
     */
    public static function PermissionTreeArray($permissions, $role_permissions = [])
    {
        $res = [];
        foreach ($permissions as $permission => $name) {
            $p = &$res;
            if($name){
                $explode_permission = explode('-', $name);
            }else{
                $explode_permission = explode('/', $permission);
                $explode_permission = array_filter($explode_permission);
            }

            $checked = in_array($permission, $role_permissions) ? true : false;
            foreach ($explode_permission as $k=>$v) {
                if(!isset($p[$v])) {
                    if ($v == end($explode_permission)) {
                        $p[$v] = ['name' => $v, 'value' => $permission, 'list'=>null];
                    } else {
                        $p[$v] = ['name' => $v, 'value' => '', 'list'=>null];
                    }
                }
                if ($checked) {
                    $p[$v]['checked'] = true;
                }
                $p = &$p[$v]['list'];
            }
        }
        $res = array_values($res);
        foreach ($res as &$value)
        {
            $value = self::filterKey($value);
        }
        return $res;
    }

    /**
     * @desc 递归过滤删除key
     * @param array $data
     * @return array
     */
    private static function filterKey(&$data = [])
    {
        if(!isset($data['list']) || !$data['list']){
            return $data;
        }
        $data['list'] = array_values($data['list']);
        foreach ($data['list'] as $key=>&$value)
        {
            $value = self::filterKey($value);
        }
        return $data;
    }
}
